<template>
  <!-- 业务待办 -->
  <div class="BusinessTodo-container">
    <div class="pub-table-select-count">
      <a-icon
        type="info-circle"
        theme="twoTone"
      />
      <span style="margin-right: 12px">
        事项总数：<span class="totalNum">{{ totalDels.todoNum || 0 }} 个 </span>
      </span>
    </div>
    <list-table
      ref="table"
      row-key="id"
      :columns="columns"
      :request="loadData"
      :alert="true"
    >
      <template
        slot="action"
        slot-scope="text, record"
      >
        <!-- noticeType等于'405'时不显示处理信息，该待办处理之后即删除 -->
        <template>
          <a
            v-if="isDone && record.noticeType.toString() !== '405'"
            :class="{ 'button-wait': wait }"
            @click="handleResolveInformation(record)"
          >处理信息</a>
          <a
            v-else
            :class="{ 'button-wait': wait }"
            @click="handleResolve(record)"
          >处理</a>
        </template>
      </template>
    </list-table>
    <DialogForm
      ref="dialogForm"
      :customFooter="true"
      :visible.sync="visible"
      edit-model="E"
      :form="dialogData.form"
      :header-title="dialogData.title"
      :width="700"
      :isEmit="false"
      :form-list="dialogData.formList"
      :rules="dialogData.rules"
      :clearForm="true"
      :styles="{ width: '450px' }"
    >
      <template
        v-if="dialogData.type == 5"
        slot="footer"
      >
        <a-button
          type="primary"
          :disabled="dialogDataResolveInfo"
          @click="handleConfirm(1)"
          class="button_right"
        > 作废
        </a-button>
        <a-button
          type="primary"
          :disabled="dialogDataResolveInfo"
          @click="handleConfirm(0)"
        >
          继续引用
        </a-button>
      </template>
      <template
        v-if="dialogData.type == 6"
        slot="footer"
      >
        <a-button
          type="primary"
          :disabled="dialogDataResolveInfo"
          class="button_right"
          @click="handleConfirm(0)"
        > 不处理
        </a-button>
        <a-button
          type="primary"
          :disabled="dialogDataResolveInfo"
          @click="handleConfirm(1)"
        >
          提交
        </a-button>
      </template>
    </DialogForm>
  </div>
</template>

<script>
import { getBusinessTodoList } from '@/api/commons.js'
import Vue from 'vue'
import DialogForm from '@/components/DialogForm' // 弹窗
import { sendInvalid, sendExpire } from '@/api/technical/specificationList'
import { actionMap } from './model.js'
import { processDetail } from '@/api/process'
import debounce from 'lodash/debounce'
const columns = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '标题',
    dataIndex: 'noticeTitle',
    width: '10%'
  },
  {
    title: '内容',
    dataIndex: 'noticeContent'
  },
  {
    title: '备注',
    dataIndex: 'remark',
    ellipsis: true,
    customRender: (text, record, index) => {
      return ['403', '404'].includes(record.noticeType) ? '' : record.remark
    }
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: '180px'
  },
  {
    title: '状态',
    width: '100px',
    dataIndex: 'statusStr'
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '80px',
    fixed: 'right',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  components: {
    DialogForm
  },
  props: {
    // 搜索额外参数
    searchQuery: {
      type: Object,
      default() {
        return {}
      }
    },
    // 消息状态  0：正常   1：关闭
    todoStatus: {
      type: [String, Number],
      default: 0
    },
    // 是否已办
    isDone: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 表头
      columns,
      totalDels: {},
      visible: false,
      dialogData: {
        dialogTitle: '',
        formList: [],
        // resolveInfo处理信息，详情页true判断只能查看
        resolveInfo: false,
        rules: {
          atlasStandardNumber: [{ required: true, message: '请输入' }],
          atlasName: [{ required: true, message: '请输入' }],
          type: [{ required: true, message: '请输入' }],
          remark: [{ required: true, message: '请输入' }]
        },
        form: { atlasStandardNumber: '', atlasName: '' }
      },
      // 按钮加载中
      wait: false
    }
  },
  computed: {
    // 是否是业务待办查看处理信息
    dialogDataResolveInfo: {
      get() {
        return this.dialogData?.resolveInfo === 'true'
      },
      set() {}
    },
    formList5() {
      return [
        {
          keyName: 'atlasStandardNumber',
          type: 'BaseInput',
          label: '图集/标准号',
          disabled: true,
          span: 24
        },
        {
          keyName: 'atlasName',
          type: 'BaseInput',
          label: '图集名称',
          disabled: true,
          span: 24
        }
      ]
    },
    formList6() {
      return [
        {
          keyName: 'atlasStandardNumber',
          type: 'BaseInput',
          label: '图集/标准号',
          disabled: this.dialogData.resolveInfo,
          span: 24
        },
        {
          keyName: 'atlasName',
          type: 'BaseInput',
          label: '图集名称',
          disabled: this.dialogData.resolveInfo,
          span: 24
        }
      ]
    }
  },
  watch: {
    $route: {
      immediate: true,
      handler() {
        this.initMessageListener()
      }
    }
  },
  created() {
    this.initPage()
  },
  methods: {
    // 弹框处理事件
    async handleConfirm(action) {
      switch (this.dialogData.type) {
        case 5:
          this.actionService(sendInvalid, action)
          break
        case 6:
          this.actionService(sendExpire, action)
          break
      }
    },
    async actionService(api, action) {
      let param = this.dialogData.form
      param.isDeleted = action
      this.$refs.dialogForm.loading = true
      const res = await api(param)
      this.visible = false
      if (res.code == 0) {
        this.$refs.table.refresh(true)
        this.$message.success('成功')
        this.$refs.dialogForm.loading = false
      } else {
        this.$refs.dialogForm.loading = false
        this.$message.success('失败')
      }
    },
    /**
     * @description: 刷新
     * @param {function}
     * @return {void}
     */
    finishDebounce: debounce(function () {
      this.refreshTable()
    }, 500),
    initMessageListener() {
      const handler = (e) => {
        const fromOrigin = e.origin || e.originalEvent.origin
        if (fromOrigin === window.location.origin) {
          // 验证是否同源，避免第三方攻击
          if (e.data === 'finish') {
            // 验证完成标志
            this.finishDebounce()
          }
        }
      }
      window.addEventListener('message', handler, false)
      this.$once('hook:beforeDestroy', () => {
        window.removeEventListener('message', handler)
      })
    },
    initPage() {
      const { needJump } = this.$route.query
      try {
        if (needJump) {
          const data = JSON.parse(needJump)
          this.$router.replace({
            path: '/matters/list/todo',
            query: {
              tabKey: 'business'
            }
          })
          this.handleResolve(data)
        }
      } catch (e) {
        console.error(e)
      }
    },
    /**
     *  刷新表格
     * @param {Boolean} flag 为true时，表格返回第一页
     */
    refreshTable(falg = true) {
      this.$refs.table.refresh(falg)
    },
    /**
     * @description: 获取必要的流程信息
     * @param {object} opinionsId 业务id
     * @return {void}
     */
    getProcessDetail(opinionsId) {
      return new Promise((resolve, reject) => {
        this.wait = true
        processDetail({ id: opinionsId })
          .then((res) => {
            if (res.code === this.SUCCESS_CODE) {
              const { procInstId, businessType, businessId, detailUrl } = res.data
              resolve({
                id: businessId,
                businessId,
                businessType,
                detailUrl,
                procInstId,
                // 取当前行业务id(避免混淆)
                opinionsId: opinionsId
              })
            } else {
              reject()
            }
          })
          .catch((error) => {
            console.log(error)
            this.$message.warning('获取流程信息失败')
            reject()
          })
          .finally(() => {
            this.wait = false
          })
      })
    },
    /**
     * 处理业务待办，这里可以根据业务需要做逻辑处理
     */
    async handleResolve(data) {
      //  if(data.noticeType == '405'){
      //   data.noticeType = '506';
      //  }
      sessionStorage.setItem('listTodoActiveKey', 'business')
      data.todoStatus = this.todoStatus
      const { noticeType } = data
      // 按钮加载中
      if (this.wait) return
      try {
        // 若是人力资源待办，则跳转到第三方人力资源系统
        if (data.sources === 2 && data.noticeType == '3') {
          let url = `https://hr.cscecxn.com${data.url}&token=${Vue.getAcloudProvider().getAccessToken()}`
          window.open(url, '_blank')
          return
        }
        // 意见征询
        if (noticeType === '501') {
          // 获取流程必要信息
          const params = await this.getProcessDetail(data.businessId)
          if (params?.procInstId) {
            const { noticeType } = data
            actionMap[noticeType] && actionMap[noticeType]({ ...data, ...params, updateId: data.businessId, todoId: data.id }, this)
          }
        } else if (noticeType === '3001') {
          window.open(`${data.url}&token=${Vue.getAcloudProvider().getAccessToken()}`, '_blank')
        } else {
          actionMap[noticeType] && actionMap[noticeType]({ ...data }, this)
        }
      } catch (error) {
        console.log(error)
      }
    },
    /**
     * @description: 处理信息
     * @param {object} data
     * @return {void}
     */
    async handleResolveInformation(data) {
      sessionStorage.setItem('listTodoActiveKey', 'business')
      data.todoStatus = this.todoStatus
      const { noticeType } = data
      try {
        // 若是人力资源待办，则跳转到第三方人力资源系统
        if (data.sources === 2 && data.noticeType == '3') {
          let url = `https://hr.cscecxn.com${data.url}&token=${Vue.getAcloudProvider().getAccessToken()}`
          window.open(url, '_blank')
          return
        }
        // 意见征询
        if (noticeType === '501') {
          // 获取流程必要信息
          const params = await this.getProcessDetail(data.businessId)
          if (params?.procInstId) {
            // resolveInfo处理信息，详情页判断只能查看
            actionMap[noticeType] && actionMap[noticeType]({ ...data, ...params, updateId: data.businessId, todoId: data.id, resolveInfo: 'true' }, this)
          }
        } else {
          actionMap[noticeType] && actionMap[noticeType]({ ...data, resolveInfo: 'true' }, this)
        }
      } catch (error) {
        console.log(error)
      }
    },
    loadData(params) {
      const userInfo = Vue.getAcloudProvider().getUserInfo()
      const requestParams = {
        ...params,
        query: { receiverId: userInfo.id, status: this.todoStatus, ...this.searchQuery }
      }
      return getBusinessTodoList(requestParams).then((res) => {
        this.totalDels = {
          todoNum: res.totalSize || 0
        }
        return res
        // return {
        //   currentPage: res.currentPage,
        //   data: res.data,
        //   totalSize: res.totalSize
        // }
      })
    }
  }
}
</script>

<style scoped>
.button-wait {
  cursor: wait;
}
</style>
